package cn.ibizlab.odoo.activiti.util;

import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;
import lombok.extern.slf4j.Slf4j;

/**
 * 工作流节点跳转辅助类
 */
@Slf4j
@Component
public class WFGoToUtil {

    @Autowired
    ManagementService managementService;
    @Autowired
    TaskService taskService;
    @Autowired
    RepositoryService repositoryService;

    //跳转方法
    public void jump(String processIntanceId, String flowElementId){

        //当前任务
        List<Task> currentTasks = taskService.createTaskQuery().processInstanceId(processIntanceId).list();
        if(currentTasks.size()==0)
            throw new ActivitiException(String.format("当前实例[%s]运行的任务",processIntanceId));

        Task currentTask=currentTasks.get(0);
        //获取流程定义
        Process process = repositoryService.getBpmnModel(currentTask.getProcessDefinitionId()).getMainProcess();
        //获取目标节点定义
        FlowNode targetNode = (FlowNode)process.getFlowElement(flowElementId);
        //删除当前运行任务
        String executionEntityId = managementService.executeCommand(new DeleteTaskCmd(currentTask.getId()));
        //流程执行到来源节点
        managementService.executeCommand(new SetFLowNodeAndGoCmd(targetNode, executionEntityId));
    }
}


